﻿using System.ComponentModel.Composition;
using Microsoft.Practices.Unity;
using VisualWip.Core;
using VisualWip.Core.Columns;
using VisualWip.Core.Interfaces;
using VisualWip.PresentationModel;

namespace VisualWip
{
    [Export(typeof(IColumnBuilder))]
    public class ColumnBuilder : IColumnBuilder
    {
        private readonly Application _application;
        private readonly IUnityContainer _container;
        private readonly IViewModelFactory _viewModelFactory;

        [ImportingConstructor]
        public ColumnBuilder(IUnityContainer container, Application application, IViewModelFactory viewModelFactory)
        {
            _container = container;
            _application = application;
            _viewModelFactory = viewModelFactory;
        }

        #region IColumnBuilder Members

        public void Build<TColumn>()
            where TColumn : Column
        {
            Build(CreateColumn<TColumn>());
        }

        public void AddColumn(Column column, bool autoSetPosition)
        {
            _application.AddColumn(column, autoSetPosition);
        }

        public TColumn CreateColumn<TColumn>() where TColumn : Column
        {
            return _container.Resolve<TColumn>();
        }


        public ISettingsWindow OpenSettings<TModel>(TModel settingsModel)
        {
            object settingsViewModel = _viewModelFactory.CreateSettingsViewModel(settingsModel);
            return ShowDialog(settingsViewModel);
        }

        #endregion

        private void Build<TColumn>(TColumn column) where TColumn : Column
        {
            ISettingsWindow dialog = OpenSettings(column);

            if (dialog.DialogResult.HasValue && dialog.DialogResult == true)
            {
                AddColumn(column, true);
            }
        }

        private ISettingsWindow ShowDialog(object columnViewModel)
        {
            var dialog = _container.Resolve<ISettingsWindow>();
            dialog.DataContext = columnViewModel;
            dialog.ShowDialog();
            return dialog;
        }
    }
}